package net.sk.china.front.service.impl.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.model.order.StoreCart;
import net.sk.china.common.model.product.StoreProduct;
import net.sk.china.common.model.product.StoreProductAttrValue;
import net.sk.china.common.model.user.User;
import net.sk.china.common.request.PageParamRequest;
import net.sk.china.common.response.CommonPage;
import net.sk.china.common.utils.DateUtil;
import net.sk.china.front.constants.Constants;
import net.sk.china.front.dao.order.StoreCartDao;
import net.sk.china.front.request.order.CartNumRequest;
import net.sk.china.front.request.order.CartRequest;
import net.sk.china.front.request.order.CartResetRequest;
import net.sk.china.front.response.order.CartInfoResponse;
import net.sk.china.front.service.order.StoreCartService;
import net.sk.china.front.service.product.StoreProductAttrValueService;
import net.sk.china.front.service.product.StoreProductService;
import net.sk.china.front.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * StoreCartServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/12 17:49
 * +----------------------------------------------------------------------
 */

@Service
public class StoreCartServiceImpl extends ServiceImpl<StoreCartDao, StoreCart> implements StoreCartService {

    @Resource
    private StoreCartDao dao;

    private final StoreProductService storeProductService;

    private final StoreProductAttrValueService storeProductAttrValueService;

    private final UserService userService;

    public StoreCartServiceImpl(StoreProductService storeProductService, StoreProductAttrValueService storeProductAttrValueService, UserService userService) {
        this.storeProductService = storeProductService;
        this.storeProductAttrValueService = storeProductAttrValueService;
        this.userService = userService;
    }

    /**
     * 根据有效标识符获取出数据
     * @param pageParamRequest 分页参数
     * @param isValid 是否失效
     * @return {@code PageInfo<CartInfoResponse>}
     */
    @Override
    public PageInfo<CartInfoResponse> getList(PageParamRequest pageParamRequest, boolean isValid) {
        User user = userService.getUserInfo();
        Page<StoreCart> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 StoreCart 类的多条件查询
        LambdaQueryWrapper<StoreCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreCart::getUid, user.getUid());
        lambdaQueryWrapper.eq(StoreCart::getStatus, isValid);
        lambdaQueryWrapper.eq(StoreCart::getIsNew, false);
        lambdaQueryWrapper.orderByDesc(StoreCart::getId);
        List<StoreCart> storeCarts = dao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(storeCarts)) {
            return CommonPage.copyPageInfo(page, new ArrayList<>());
        }

        List<CartInfoResponse> response = new ArrayList<>();
        for (StoreCart storeCart : storeCarts) {
            CartInfoResponse cartInfoResponse = new CartInfoResponse();
            BeanUtils.copyProperties(storeCart, cartInfoResponse);
            // 获取商品信息
            StoreProduct storeProduct = storeProductService.getCartByProId(storeCart.getProductId());
            cartInfoResponse.setImage(storeProduct.getImage());
            cartInfoResponse.setStoreName(storeProduct.getStoreName());

            if (!isValid) {// 失效商品直接掠过
                cartInfoResponse.setAttrStatus(false);
                response.add(cartInfoResponse);
                continue ;
            }

            // 获取对应的商品规格信息(只会有一条信息)
            List<StoreProductAttrValue> attrValueList = storeProductAttrValueService.getListByProductIdAndAttrId(storeCart.getProductId(),
                    storeCart.getProductAttrUnique(), Constants.NUM_ZERO);
            // 规格不存在即失效
            if (CollUtil.isEmpty(attrValueList)) {
                cartInfoResponse.setAttrStatus(false);
                response.add(cartInfoResponse);
                continue ;
            }
            StoreProductAttrValue attrValue = attrValueList.get(0);
            if (StrUtil.isNotBlank(attrValue.getImage())) {
                cartInfoResponse.setImage(attrValue.getImage());
            }
            cartInfoResponse.setAttrId(attrValue.getId());
            cartInfoResponse.setSuk(attrValue.getSuk());
            cartInfoResponse.setPrice(attrValue.getPrice());
            cartInfoResponse.setAttrId(attrValue.getId());
            cartInfoResponse.setAttrStatus(attrValue.getStock() > 0);
            cartInfoResponse.setStock(attrValue.getStock());
            response.add(cartInfoResponse);
        }
        return CommonPage.copyPageInfo(page, response);
    }

    /**
     * 新增购物车
     * @param storeCartRequest 新增购物车参数
     * @return {@code Long}
     */
    @Override
    public Long saveCate(CartRequest storeCartRequest) {
        // 判断商品正常
        StoreProduct product = storeProductService.getById(storeCartRequest.getProductId());
        if (ObjectUtil.isNull(product) || product.getIsDel() || !product.getIsShow()) {
            throw new TalkException("未找到对应商品");
        }
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.getListByProductIdAndAttrId(product.getId(), storeCartRequest.getProductAttrUnique(), Constants.NUM_ZERO);
        if (CollUtil.isEmpty(attrValues)) {
            throw new TalkException("未找到对应的商品SKU");
        }

        // 普通商品部分(只有普通商品才能添加购物车)、是否已经有同类型商品在购物车，有则添加数量没有则新增
        User user = userService.getUserInfo();
        StoreCart storeCartPram = new StoreCart();
        storeCartPram.setProductAttrUnique(String.valueOf(storeCartRequest.getProductAttrUnique()));
        storeCartPram.setUid(user.getUid());
        List<StoreCart> existCarts = getByEntity(storeCartPram);
        if (existCarts.size() > 0) {
            // 购物车添加数量
            StoreCart forUpdateStoreCart = existCarts.get(0);
            forUpdateStoreCart.setCartNum(forUpdateStoreCart.getCartNum() + storeCartRequest.getCartNum());
            boolean updateResult = dao.updateById(forUpdateStoreCart) >= 1;
            if (!updateResult) throw new TalkException("添加购物车失败");

            return forUpdateStoreCart.getId();
        } else {
            // 新增购物车数据
            StoreCart storeCart = new StoreCart();
            BeanUtils.copyProperties(storeCartRequest, storeCart);
            storeCart.setUid(user.getUid());
            storeCart.setType("product");
            if (dao.insert(storeCart) <= 0) throw new TalkException("添加购物车失败");

            return storeCart.getId();
        }
    }

    /**
     * 删除购物车
     * @param ids 待删除id
     * @return {@code boolean}
     */
    @Override
    public boolean deleteCartByIds(List<Long> ids) {
        return dao.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取当前购物车数量
     * @param request 请求参数
     * @return Map<String, Long>
     */
    @Override
    public Map<String, Long> getCount(CartNumRequest request) {
        User user = userService.getUserInfo();
        Map<String, Long> map = new HashMap<>();
        Long num;
        if (request.getType().equals("total")) {
            num = getUserCountByStatus(user.getUid(), request.getNumType());
        } else {
            num = getUserSumByStatus(user.getUid(), request.getNumType());
        }
        map.put("count", num);

        return map;
    }

    /**
     * 修改购物车商品数量
     * @param id 购物车id
     * @param number 数量
     * @return {@code boolean}
     */
    @Override
    public boolean updateCartNum(Integer id, Integer number) {
        if (ObjectUtil.isNull(number)) throw new TalkException("商品数量不合法");
        if (number <= 0 || number > 99) throw new TalkException("商品数量不能小于1大于99");
        StoreCart storeCart = getById(id);
        if (ObjectUtil.isNull(storeCart)) throw new TalkException("当前购物车不存在");
        if (storeCart.getCartNum().equals(number)) return true;
        storeCart.setCartNum(number);
        return updateById(storeCart);
    }

    /**
     * 购物车重选提交
     * @param resetRequest 重选数据
     * @return {@code boolean}
     */
    @Override
    public boolean resetCart(CartResetRequest resetRequest) {
        LambdaQueryWrapper<StoreCart> query = new LambdaQueryWrapper<>();
        query.eq(StoreCart::getId, resetRequest.getId());
        StoreCart storeCart = dao.selectOne(query);
        if (ObjectUtil.isNull(storeCart)) throw new TalkException("购物车不存在");
        if (ObjectUtil.isNull(resetRequest.getNum()) || resetRequest.getNum() <= 0 || resetRequest.getNum() >= 999) {
            throw new TalkException("数量不合法");
        }

        storeCart.setCartNum(resetRequest.getNum());
        storeCart.setProductAttrUnique(resetRequest.getUnique() + "");
        boolean updateResult = dao.updateById(storeCart) > 0;
        if (!updateResult) {
            throw new TalkException("重选添加购物车失败");
        }
        productStatusEnableFlag(resetRequest.getId(), true);

        return true;
    }

    /**
     * 通过id和uid获取购物车信息
     * @param id 购物车id
     * @param uid 用户uid
     * @return {@code StoreCart}
     */
    @Override
    public StoreCart getByIdAndUid(Long id, Integer uid) {
        LambdaQueryWrapper<StoreCart> query = new LambdaQueryWrapper<>();
        query.eq(StoreCart::getId, id).eq(StoreCart::getUid, uid).eq(StoreCart::getIsNew, false).eq(StoreCart::getStatus, true);

        return dao.selectOne(query);
    }

    /**
     * 购物车基本查询
     * @param storeCart 购物车参数
     * @return {@code List<StoreCart>}
     */
    private List<StoreCart> getByEntity(StoreCart storeCart) {
        LambdaQueryWrapper<StoreCart> query = new LambdaQueryWrapper<>();
        query.setEntity(storeCart);

        return dao.selectList(query);
    }

    /**
     * 购物车商品数量
     * @param userId Integer 用户id
     * @param status Boolean 商品类型：true-有效商品，false-无效商品
     * @return {@code Long}
     */
    private Long getUserCountByStatus(Integer userId, Boolean status) {
        LambdaQueryWrapper<StoreCart> query = new LambdaQueryWrapper<>();
        query.eq(StoreCart::getUid, userId);
        query.eq(StoreCart::getStatus, status);
        query.eq(StoreCart::getIsNew, false);

        return dao.selectCount(query);
    }

    /**
     * 购物车购买商品总数量
     * @param userId Integer 用户id
     * @param status 商品类型：true-有效商品，false-无效商品
     * @return {@code Long}
     */
    private Long getUserSumByStatus(Integer userId, Boolean status) {
        QueryWrapper<StoreCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("ifnull(sum(cart_num), 0) as id");
        queryWrapper.eq("uid", userId);
        queryWrapper.eq("is_new", false);
        queryWrapper.eq("status", status);
        StoreCart storeCart = dao.selectOne(queryWrapper);
        if (ObjectUtil.isNull(storeCart)) {
            return 0L;
        }
        return storeCart.getId();
    }

    /**
     * 根据购物车id更新状态
     * @param carId 购物车id
     * @param flag 待更新状态值
     * @return 更新结果
     */
    private boolean productStatusEnableFlag(Long carId, Boolean flag) {
        StoreCart storeCartPram = new StoreCart();
        storeCartPram.setId(carId);
        List<StoreCart> existStoreCartProducts = getByEntity(storeCartPram);
        if(ObjectUtil.isNull(existStoreCartProducts)) return false;
        existStoreCartProducts = existStoreCartProducts.stream().map(e->{
            e.setStatus(flag);
            return e;
        }).collect(Collectors.toList());
        return updateBatchById(existStoreCartProducts);
    }
}
